package com.baijiaxing.weixin.family.service.impl;

import com.baijiaxing.weixin.family.common.aes.AesException;
import com.baijiaxing.weixin.family.common.aes.WXBizMsgCrypt;
import com.baijiaxing.weixin.family.common.consts.FamilyConsts;
import com.baijiaxing.weixin.family.message.enums.FamilyMessageTypeEnum;
import com.baijiaxing.weixin.family.message.model.FamilyImageMessage;
import com.baijiaxing.weixin.family.message.model.FamilyTextMessage;
import com.baijiaxing.weixin.family.message.units.CreateFamilyImageMessage;
import com.baijiaxing.weixin.family.message.units.CreateFamilyTextMessage;
import com.baijiaxing.weixin.family.message.units.FamilyMessageUnits;
import com.baijiaxing.weixin.family.client.service.FamilyMessageService;
import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * Created by June on 2016/12/17.
 */
@Service
public class FamilyMessageServiceImpl implements FamilyMessageService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public String responseDecryptMsg(String sReqMsgSig, String sReqTimeStamp, String sReqNonce, String sReqData) throws AesException, DocumentException {
        WXBizMsgCrypt wxcpt = FamilyConsts.getWXBizMsgCrypt();
        String sMsg = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData);
        if (StringUtils.isBlank(sMsg)) {
            return null;
        }
        logger.info("===解密后的消息===sMsg:{}", sMsg);
        String responseXml = "";
        //如果接收的是文本消息
        if (FamilyMessageUnits.getMsgType(sMsg).equals(FamilyMessageTypeEnum.TEXT.getKey())) {
            //解密消息
            FamilyTextMessage textMessage = CreateFamilyTextMessage.parseText(sMsg);
            //自动回复文本消息
            responseXml = CreateFamilyTextMessage.replyText(textMessage.getContent(), textMessage.getFromUserName(), textMessage.getToUserName());
        }

        if (FamilyMessageUnits.getMsgType(sMsg).equals(FamilyMessageTypeEnum.IMAGE.getKey())) {
            //解密消息
            FamilyImageMessage imageMessage = CreateFamilyImageMessage.parseImage(sMsg);
            responseXml = CreateFamilyImageMessage.replyImage(imageMessage.getMediaId(), imageMessage.getFromUserName(), imageMessage.getToUserName());
        }

        //添加消息

        //添加消息结束

        if (StringUtils.isBlank(responseXml)) {
            return null;
        }
        logger.info("回复数据 responseXml{}", responseXml);
        //消息加密
        String resEntry = wxcpt.EncryptMsg(responseXml, sReqTimeStamp, sReqNonce);
        return resEntry;
    }
}
